#include "EagerLogger.h"
#include <ctime>
#include <filesystem>
#include <cstring>

namespace fs = std::filesystem;

// 在类外直接初始化静态成员变量，这就是饿汉式的关键
EagerLogger* EagerLogger::instance = new EagerLogger();

EagerLogger::EagerLogger() {
    fs::path path0 = fs::absolute("eager_app.log");
    std::cout << "- Eager Logger file path: " << path0.string() << std::endl;
    std::cerr << "- eager logger " << this << std::endl;
    logFile.open(path0, std::ios::app);
    if (!logFile.is_open()) {
        std::cerr << "- cannot open eager log file" << std::endl;
    }
}

EagerLogger::~EagerLogger() {
    if (logFile.is_open()) {
        logFile.close();
    }
}

EagerLogger* EagerLogger::getInstance() {
    return instance;
}

void EagerLogger::log(const std::string& message) {
    if (logFile.is_open()) {
        time_t now = time(0);
        char* dt = ctime(&now);
        dt[strlen(dt) - 1] = '\0'; // 移除换行符
        logFile << "[" << dt << "] INFO: " << message << std::endl;
    }
}

void EagerLogger::logError(const std::string& message) {
    if (logFile.is_open()) {
        time_t now = time(0);
        char* dt = ctime(&now);
        dt[strlen(dt) - 1] = '\0';
        logFile << "[" << dt << "] ERROR: " << message << std::endl;
    }
}

void EagerLogger::logWarning(const std::string& message) {
    if (logFile.is_open()) {
        time_t now = time(0);
        char* dt = ctime(&now);
        dt[strlen(dt) - 1] = '\0';
        logFile << "[" << dt << "] WARNING: " << message << std::endl;
    }
} 